//
//  StaffProfileViewController.m
//  APJ Resource
//
//  Created by Richard Zhao on 2/15/14.
//  Copyright (c) 2014 APJ. All rights reserved.
//

#import "StaffProfileViewController.h"
//#import "LSTabItem.h"
//#import "VerticalScrollTabBarView.h"
//#import "MultiTabControl.h"
#import "Staff.h"
#import "Dept.h"
#import "HRStore.h"
#import "InterviewController.h"
#import "EducationBackgroundController.h"
#import "WorkExperienceController.h"
#import "QualificationController.h"
#import "StaffSkillMatrixController.h"
#import "IQGanttView.h"
#import "IQScrollView.h"
#import "ProjectAllocation.h"
#import "Project.h"
#import "Const.h"

@interface StaffProfileViewController ()

@end

@implementation StaffProfileViewController
{
//    VerticalScrollTabBarView *tabView;
}

@synthesize staff;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg"]]];
    contentView.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
    
//    borderImage.image = [UIImage imageNamed:@"scrolltabs_border"];
    //backgroundImage.image = [UIImage imageNamed:@"controlpanel_view_background"];
//    [contentView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"controlpanel_view_background"]]];
    
   
//    LSTabItem *item1 = [[LSTabItem alloc] initWithTitle:@"Education Background"];
//    LSTabItem *item2 = [[LSTabItem alloc] initWithTitle:@"Work Experience"];
//    LSTabItem *item3 = [[LSTabItem alloc] initWithTitle:@"Qualification Certificate"];
//    LSTabItem *item4 = [[LSTabItem alloc] initWithTitle:@"Skill Set"];
//    LSTabItem *item5 = [[LSTabItem alloc] initWithTitle:@"Project Allocation"];
//    NSArray *tabItems = [NSArray arrayWithObjects:item1, item2, item3, item4, item5, nil];

    
    // Assigns some badge number
    //((LSTabItem *)tabItems[0]).badgeNumber = 10;
    
//    tabView = [[VerticalScrollTabBarView alloc] initWithItems:tabItems delegate:self];
//    tabView.autoresizingMask |= UIViewAutoresizingFlexibleHeight;
//    tabView.itemPadding = -50.0f;
//    tabView.margin = 0.0f;
//    tabView.frame = CGRectMake(0.0f, 235.0f, 76.0f, self.view.bounds.size.height);
//    [self.view addSubview:tabView];
    
    [self displayStaffBasicInfo];
    
    
    // setup segment control
    [staffDetailSegment addTarget:self action:@selector(detailChanged:) forControlEvents:UIControlEventValueChanged];
    
    staffDetailSegment.selectedSegmentIndex = 0;
    // 第一次进入此页面时，不进入教育背景，而是进入面试结果。
    //[self loadEducationBackground];
    [self loadInterview];
    
    UIBarButtonItem *bookmark = [[UIBarButtonItem alloc] initWithTitle:@"Put in Bookmarks" style:UIBarButtonItemStylePlain target:self action:@selector(changeBookMark:)];
    [[self navigationItem] setRightBarButtonItem:bookmark];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self setBookmarkButton];
}

- (void) setBookmarkButton
{
    NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirector = [documentDirectories objectAtIndex:0];
    NSString *path =[documentDirector stringByAppendingPathComponent:BOOKMAKE_FILE_NAME];
    
    NSArray *bookmarks = [NSArray arrayWithContentsOfFile:path];
    
    if (bookmarks && bookmarks.count > 0) {
        for (NSNumber *staffId in bookmarks) {
            if (staffId.intValue == staff.staffId) {
                [[[self navigationItem] rightBarButtonItem] setTitle:@"Remove from Bookmarks"];
                break;
            }
        }
    }
    
//    NSData *data = [NSData dataWithContentsOfFile:path];
//    if (data && data.length > 0) {
//        NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
//        NSArray *bookmarks = [unArchiver decodeObjectForKey:@"bookmarks"];
//        
//        for (NSNumber *staffId in bookmarks) {
//            if (staffId.intValue == staff.staffId) {
//                [[[self navigationItem] rightBarButtonItem] setTitle:@"Remove from Bookmarks"];
//                break;
//            }
//        }
//    }
    
}

- (void)changeBookMark:(id)sender
{
    NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirector = [documentDirectories objectAtIndex:0];
    NSString *path =[documentDirector stringByAppendingPathComponent:BOOKMAKE_FILE_NAME];
    
    NSMutableArray *bookmarks = [NSMutableArray arrayWithContentsOfFile:path];
    
    if (bookmarks && bookmarks.count > 0) {

    } else {
        bookmarks = [[NSMutableArray alloc] init];
    }
    
    if ([self.navigationItem.rightBarButtonItem.title isEqualToString:@"Put in Bookmarks"]) {
        [bookmarks addObject:[NSNumber numberWithInt:staff.staffId]];
        [[[self navigationItem] rightBarButtonItem] setTitle:@"Remove from Bookmarks"];
    } else {
        [bookmarks removeObject:[NSNumber numberWithInt:staff.staffId]];
        [[[self navigationItem] rightBarButtonItem] setTitle:@"Put in Bookmarks"];
    }
    
    [bookmarks writeToFile:path atomically:YES];
}

- (void)displayStaffBasicInfo
{
    NSDictionary *sex = [NSDictionary dictionaryWithObjectsAndKeys:@"Male", @"M", @"Female", @"F", nil];
    
    nameLabel.text = staff.chineseName;
    jobTitleLabel.text = staff.jobTitle;
    sexLabel.text = [sex valueForKey:staff.sex];
    if (staff.dateOfBirth < 1) {
        ageLabel.text = @"";
    } else {
        NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
        int age = (now - staff.dateOfBirth) / 3600 / 24 / 365;
        if (age > 10) {
            ageLabel.text = [NSString stringWithFormat:@"%d years old",age];
        } else {
            ageLabel.text = @"";
        }
    }
    englishNameLabel.text = staff.englishName;
    staffNoLabel.text = staff.staffNo;
    deptLabel.text = [[HRStore sharedStore] findDeptById:staff.deptId].deptFullName;
    emailLabel.text = staff.companyEmail;
    phoneLabel.text = staff.mobilePhoneNo;
    statusLabel.text = staff.staffStatus;
    
    NSString *imgPath = [NSString stringWithFormat:@"%d.png", staff.staffId];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:imgPath];
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        [photoImage setImage:[UIImage imageWithContentsOfFile:path]];
    } else {
        [photoImage setImage:[UIImage imageNamed:@"defaultPhoto"]];
    }
}

- (void)detailChanged:(id)sender
{
    [self hideAll];
    switch ([sender selectedSegmentIndex]) {
        case 0:
            [self loadInterview];
            break;
        case 1:
            [self loadEducationBackground];
            break;
        case 2:
            [self loadWorkExperience];
            break;
        case 3:
            [self loadQualification];
            break;
        case 4:
            [self loadStaffSkillMatrix];
            break;
        default:
            break;
    }
    // 项目列表：[self loadProjectAssign];
}

//- (void)tabBar:(LSTabBarView *)tabBar
//   tabSelected:(LSTabItem *)item
//       atIndex:(NSInteger)selectedIndex
//{
//    [self hideAll];
//    switch (selectedIndex) {
//        case 0:
//            [self loadEducationBackground];
//            break;
//        case 1:
//            [self loadWorkExperience];
//            break;
//        case 2:
//            [self loadQualification];
//            break;
//        case 3:
//            [self loadStaffSkillMatrix];
//            break;
//        case 4:
//            [self loadProjectAssign];
//            break;
//        default:
//            break;
//    }
//
//}

- (void)loadInterview
{
    if (!interviewTable)
    {
        CGRect frame = CGRectMake(contentView.bounds.origin.x + 50,
                                  contentView.bounds.origin.y,
                                  contentView.bounds.size.width - 50,
                                  contentView.bounds.size.height);
        interviewTable = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
        UINib *nib = [UINib nibWithNibName:@"StaffInterviewCell" bundle:nil];
        [interviewTable registerNib:nib forCellReuseIdentifier:@"interview"];
        interviewController = [[InterviewController alloc] initWithStaffId:staff.staffId];
        interviewTable.dataSource = interviewController;
        interviewTable.delegate = interviewController;
        [interviewTable setBackgroundColor:[UIColor colorWithWhite:0 alpha:0]];
        [contentView addSubview:interviewTable];
    }
    [interviewTable setHidden:NO];
}

- (void)loadEducationBackground
{
    if (!eduTable)
    {
        CGRect frame = CGRectMake(contentView.bounds.origin.x + 50,
                                  contentView.bounds.origin.y,
                                  contentView.bounds.size.width - 50,
                                  contentView.bounds.size.height);
        eduTable = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
        UINib *nib = [UINib nibWithNibName:@"EducationBackgroundCell" bundle:nil];
        [eduTable registerNib:nib forCellReuseIdentifier:@"education"];
        eduController = [[EducationBackgroundController alloc] initWithStaffId:staff.staffId];
        eduTable.dataSource = eduController;
        eduTable.delegate = eduController;
        [eduTable setBackgroundColor:[UIColor colorWithWhite:0 alpha:0]];
        [contentView addSubview:eduTable];
    }
    [eduTable setHidden:NO];
}

- (void)loadWorkExperience
{
    if (!workTable)
    {
        CGRect frame = CGRectMake(contentView.bounds.origin.x + 50,
                                  contentView.bounds.origin.y,
                                  contentView.bounds.size.width - 50,
                                  contentView.bounds.size.height);
        workTable = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
        UINib *nib = [UINib nibWithNibName:@"WorkExperienceCell" bundle:nil];
        [workTable registerNib:nib forCellReuseIdentifier:@"work"];
        workController = [[WorkExperienceController alloc] initWithStaffId:staff.staffId];
        workTable.dataSource = workController;
        workTable.delegate = workController;
        [workTable setBackgroundColor:[UIColor colorWithWhite:0 alpha:0]];
        [contentView addSubview:workTable];
    }
    [workTable setHidden:NO];
}

- (void)loadQualification
{
    if (!qualTable)
    {
        CGRect frame = CGRectMake(contentView.bounds.origin.x + 50,
                                  contentView.bounds.origin.y,
                                  contentView.bounds.size.width - 50,
                                  contentView.bounds.size.height);
        qualTable = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
        UINib *nib = [UINib nibWithNibName:@"QualificationCell" bundle:nil];
        [qualTable registerNib:nib forCellReuseIdentifier:@"qual"];
        qualController = [[QualificationController alloc] initWithStaffId:staff.staffId];
        qualTable.dataSource = qualController;
        qualTable.delegate = qualController;
        [qualTable setBackgroundColor:[UIColor colorWithWhite:0 alpha:0]];
        [contentView addSubview:qualTable];
    }
    [qualTable setHidden:NO];
}

- (void)loadStaffSkillMatrix
{
    if (!matrixTable)
    {
        CGRect frame = CGRectMake(contentView.bounds.origin.x + 50,
                                  contentView.bounds.origin.y + 30,
                                   550,
                                  contentView.bounds.size.height);
        matrixTable = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
        matrixController = [[StaffSkillMatrixController alloc] initWithStaffId:staff.staffId];
        matrixTable.dataSource = matrixController;
        matrixTable.delegate = matrixController;
        [matrixTable setBackgroundColor:[UIColor colorWithWhite:0 alpha:0]];
        [contentView addSubview:matrixTable];
    }
    [matrixTable setHidden:NO];
}

- (void)loadProjectAssign
{
    if (!gantt)
    {
//        CGRect frame = CGRectMake(contentView.bounds.origin.x + 10,
//                                  contentView.bounds.origin.y + 10,
//                                  contentView.bounds.size.width - 20,
//                                  contentView.bounds.size.height - 110);
        CGRect frame = contentView.bounds;
        NSArray *colors = [NSArray arrayWithObjects:[UIColor greenColor], [UIColor yellowColor], [UIColor blueColor], [UIColor redColor], [UIColor purpleColor], [UIColor orangeColor], [UIColor grayColor], nil];
        gantt = [[IQGanttView alloc] initWithFrame:frame];
        //gantt.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
        [contentView addSubview:gantt];
        
        
        // add process bar for each project
        double ganttWidth = 3072.937944;
        double scope = gantt.scaleWindow.windowEnd - gantt.scaleWindow.windowStart;
        NSArray *projectAssign = [[HRStore sharedStore] projectAssignToStaff:staff.staffId];
        int i=0;
        for (ProjectAllocation *allocation in projectAssign) {
            UIProgressView *pro = [[UIProgressView alloc] init];
            NSTimeInterval start = [[NSDate dateWithTimeIntervalSince1970:allocation.startDate] timeIntervalSinceReferenceDate];
            NSTimeInterval end = [[NSDate dateWithTimeIntervalSince1970:allocation.endDate] timeIntervalSinceReferenceDate];        
            double startPoint = start - gantt.scaleWindow.windowStart;
            double endPoint = end - gantt.scaleWindow.windowStart;
            double x1 = (ganttWidth / scope) * startPoint;
            double x2 = (ganttWidth / scope) * endPoint;
            [pro setFrame:CGRectMake(x1, 80*i+40, x2-x1, 100)];
            CGAffineTransform transform = CGAffineTransformMakeScale(1.0f, 3.0f);
            pro.transform = transform;
            [pro setTrackTintColor:[colors objectAtIndex:i%colors.count]];
            [gantt addSubview:pro];
            
            UILabel *projectName = [[UILabel alloc] init];
            Project *project = [[HRStore sharedStore] findProjectById:allocation.projectId];
            projectName.text = project.projectShortName;
            [projectName setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0]];
            [projectName sizeToFit];
            [projectName setCenter:CGPointMake(x1+(x2-x1)/2, 80*i+55)];
            [gantt addSubview:projectName];
            
            UILabel *startDate = [[UILabel alloc] init];
            NSDate *sDate = [NSDate dateWithTimeIntervalSince1970:allocation.startDate];
            NSDateFormatter *formate = [[NSDateFormatter alloc] init];
            [formate setDateFormat:@"dd/MMM"];
            startDate.text = [formate stringFromDate:sDate];
            startDate.font = [UIFont italicSystemFontOfSize:12.0];
            [startDate setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0]];
            [startDate sizeToFit];
            [startDate setCenter:CGPointMake(x1-23, 80*i+44)];
            [gantt addSubview:startDate];
            
            UILabel *endDate = [[UILabel alloc] init];
            NSDate *eDate = [NSDate dateWithTimeIntervalSince1970:allocation.endDate];
            endDate.text = [formate stringFromDate:eDate];
            endDate.font = [UIFont italicSystemFontOfSize:12.0];
            [endDate setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0]];
            [endDate sizeToFit];
            [endDate setCenter:CGPointMake(x2+23, 80*i+44)];
            [gantt addSubview:endDate];
            
            i++;
        }
    }
    
    [gantt setHidden:NO];
}

- (void)hideAll
{
    [interviewTable setHidden:YES];
    [eduTable setHidden:YES];
    [workTable setHidden:YES];
    [qualTable setHidden:YES];
    [matrixTable setHidden:YES];
    [gantt setHidden:YES];
}

//- (LSTabControl *)tabBar:(LSTabBarView *)tabBar
//          tabViewForItem:(LSTabItem *)item
//                 atIndex:(NSInteger)index
//{
//    return [[MultiTabControl alloc] initWithItem:item];
//}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
